<template>
  <div class="setting-container">
    <!-- app-container提供了内边距 -->
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="active">
          <el-tab-pane label="角色管理" name="role">
            <el-button type="primary" size="small" @click="isShow = true"> <i class="el-icon-plus" /> 新增角色</el-button>

            <!-- 表格 -->
            <el-table :data="list" style="margin: 10px 0">
              <el-table-column label="序号" type="index" :index="indexFn" width="80" />
              <el-table-column label="角色名称" prop="name" width="150" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <!--
                  <slot name="default" :row="item" :$index="index"></slot>
                  obj = { row: item, $index: index }

                  <template #default="obj"></template>
                 -->
                <template #default="{row}">
                  <!-- {{ obj.row }} -->
                  <el-button size="small" type="success" @click="assign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <!--
              current-page 当前页
              page-sizes 提供给用户去选择的每页条数的选项
              page-size 每页条数
              layout 布局控件
              total 总数
              @size-change="handleSizeChange"  每页条数变化 , 触发
              @current-change="handleCurrentChange"  页码变化, 触发
             -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1,2,3,4,5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 :closable="false" 关闭 手动关闭功能 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 添加角色 -->
      <el-dialog
        :title="showTitle"
        :visible="isShow"
        @close="closeDialog"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <!--
          组件内部:
          <slot name="footer" />
         -->

        <template #footer>
          <el-button size="small" type="primary" @click="clickSubmit">确认</el-button>
          <el-button size="small">取消</el-button>
        </template>
      </el-dialog>

      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="closeAssignDialog"
      >
        <!--
          el-tree
            show-checkbox  展示多选框, 选择树形节点
            check-strictly  父子级不关联
         -->
        <el-tree
          ref="tree"
          node-key="id"
          show-checkbox
          check-strictly
          default-expand-all
          :data="permissionList"
          :props="{ label: 'name' }"
        />
        <template #footer>
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="clickAssignSubmit">确定</el-button>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { reqAddRole, reqAssignPerm, reqDelRole, reqGetRoleDetail, reqGetRoleList, reqUpdateRole } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { transList2TreeData } from '@/utils'
export default {
  name: 'Settings',
  data() {
    return {
      active: 'role',
      list: [],
      page: 1, // 当前页码
      pagesize: 3, // 每页条数
      total: 0, // 总数
      loading: false,
      isShow: false,
      form: {
        // 接口文档
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['change', 'blur'] }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: ['change', 'blur'] }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      permissionList: [], // 树形的权限列表
      roleId: '' // 存储当前操作的角色id, 将来拿着id发请求分配权限
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      // console.log(res, 6754)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      // 每页条数变化时
      this.pagesize = val
      // 规范: 每页条数变化时, 重置成第一页!!!
      // 一共100条 1条/页,  用户在第80页 => 合理
      // 一共100条 100条/页,  用户应该在第一页
      this.page = 1

      this.getRoleList()

      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      // 页码变化时,
      this.page = val
      this.getRoleList()
      // console.log(`当前页: ${val}`)
    },
    indexFn(val) {
      // val 0 1 2 3...   返回值作为索引展示
      // 前面多少条 = 前面有多少页 * 每页条数
      return val + 1 + (this.page - 1) * this.pagesize
    },
    del(id) {
      // console.log(`我要被删除了${id}`)
      this.$confirm('要不要删呀? 你确认么? 你真的确认么?', '提示', { type: 'warning' }).then(async() => {
        const res = await reqDelRole(id)
        this.$message.success(res.message)
        // console.log(res)

        // 如果发现这是此页最后一条数据, 往前翻一页
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }

        this.getRoleList()
      }).catch(() => {
        console.log('取消')
      })
    },
    closeDialog() {
      this.isShow = false

      // 重置表单 移除校验结果(resetFields只会清空表单之内的数据)
      this.$refs.form.resetFields()

      // 编辑/添加 共用同一个对话框  => 手动清空
      this.form = {
        name: '',
        description: ''
      }
    },
    clickSubmit() {
      this.$refs.form.validate(async flag => {
        if (!flag) return

        if (this.form.id) {
          // 编辑
          const res = await reqUpdateRole(this.form)
          // console.log(res)
          this.$message.success(res.message)
        } else {
          // 添加
          const res = await reqAddRole(this.form)
          // console.log(res)
          // 提示
          this.$message.success(res.message)
        }

        // 关闭对话框
        this.isShow = false
        // 获取数据重新渲染
        this.getRoleList()
      })
    },
    async edit(id) {
      const { data } = await reqGetRoleDetail(id)
      // console.log(res, 9999)
      this.isShow = true
      this.form = data
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      // this.companyForm = data
      console.log(data, 6666)
      this.companyForm = data
    },
    closeAssignDialog() {
      this.showAssignDialog = false

      // 关闭 时. 让树形节点都不选中
      this.$refs.tree.setCheckedKeys([])
    },
    async assign(id) {
      console.log(id)
      this.showAssignDialog = true

      this.roleId = id

      // 1.获取所有权限列表
      const { data } = await reqGetPermissionList()
      // console.log(res)
      // 列表数据=>树形数据
      this.permissionList = transList2TreeData(data, '0')

      // 2.获取这个角色之前的权限 进行回显
      const { data: { permIds }} = await reqGetRoleDetail(id)
      // console.log(res)
      // permIds => 角色之前的权限id组成的数组
      // 设置树形节点的选中 => 调用tree组件的方法(ref node-key)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    async clickAssignSubmit() {
      // 如何获取树形节点的选中数组
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log(permIds)
      const res = await reqAssignPerm(this.roleId, permIds)
      console.log(res)
      // 提示
      this.$message.success(res.message)
      // 关闭
      this.closeAssignDialog()
    }
  }
}
</script>

<style>

</style>
